//
//  LTPickerView.m
//  protoBuffer
//
//  Created by chenfujie on 15/11/20.
//  Copyright © 2015年 Meeno04. All rights reserved.
//

#define LTColor(r, g, b, a) [UIColor colorWithRed:(r) / 255.0 green:(g) / 255.0 blue:(b) / 255.0 alpha:(a)]
#define Screen_Width [[UIScreen mainScreen] bounds].size.width
#define Screen_Height [[UIScreen mainScreen] bounds].size.height
#define pickselecolor [UIColor colorWithRed:3.0 / 255.0 green:160.0 / 255.0 blue:152.0 / 255.0 alpha:1.00f]

#import "LTPickerView.h"
//#import "TXAdapter.h"
#import "HeaderConfig.h"

// #import <POP.h>
@interface LTPickerView () <UIPickerViewDataSource, UIPickerViewDelegate>
@property(strong, nonatomic) IBOutlet UIView *contentView;
@property(weak, nonatomic) IBOutlet UIPickerView *myPickerView;
@property(weak, nonatomic) IBOutlet UIToolbar *myToolbar;
@property(nonatomic, strong) UIWindow *window;
@property(nonatomic, strong) UITapGestureRecognizer *gesture;
@property(nonatomic, strong) UIView *view;
@property(nonatomic) NSInteger box;
@property(nonatomic) NSInteger indxi;
@property(weak, nonatomic) IBOutlet UIButton *titleBtn;
@property(nonatomic) int honk;
@property(nonatomic, strong) UIView *v;
@property(nonatomic, strong) UIImageView *imv;
@property(weak, nonatomic) IBOutlet UILabel *Titlab;

@end
@implementation LTPickerView
- (void)awakeFromNib {
    [self loadNibFile];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.contentView.frame = self.bounds;
}

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}
- (void)loadNibFile {
    NSBundle *containnerBundle = [NSBundle bundleForClass:[self class]];
    NSBundle *resourceBundle = [NSBundle bundleWithPath:[containnerBundle pathForResource:@"oneCommonLib" ofType:@"bundle"]];
    [resourceBundle loadNibNamed:@"LTPickerView" owner:self options:nil];
}
- (void)loadUI {
    [self addSubview:self.contentView];
    if (self.title) {
        [self.titleBtn setTitle:self.title forState:UIControlStateNormal];
        [self.titleBtn setTitle:self.title forState:UIControlStateHighlighted];
    }

    self.Titlab.font = [UIFont boldSystemFontOfSize:tRealFontSize(19)];
    self.Titlab.textColor = cust_Color(51, 51, 51, 1);
    self.Titlab.text = self.title;

    [self.titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.myToolbar.items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      UIBarButtonItem *itemBtn = (UIBarButtonItem *)obj;
      NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
      [itemBtn setTitleTextAttributes:attributes forState:UIControlStateNormal];
    }];
    _window = [UIApplication sharedApplication].keyWindow;
    // 给window加点击手势关闭self
    _gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
    [_window addGestureRecognizer:_gesture];

    _view = [[UIView alloc] initWithFrame:_window.bounds];
    _view.backgroundColor = LTColor(0, 0, 0, 0.45);
    [_window addSubview:_view];
    [_view addSubview:self];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(MMK)];
    [self addGestureRecognizer:tap];

    //    UIView *v =  [[UIView alloc] initWithFrame:CGRectMake(15, iphone_height-30, iphone_width-30, 30)];
    //    _v = v;

    //    v.backgroundColor = [UIColor whiteColor];
    //    [_view addSubview:v];
    UIImageView *imv = [[UIImageView alloc] initWithFrame:CGRectZero];
    imv.image = [UIImage imageNamed:@"home_btn_dropdown"];
    imv.contentMode = UIViewContentModeCenter;
    _imv = imv;
    [_view addSubview:imv];

    if (kIS_iPhoneX) {
        self.frame = CGRectMake(15, iphone_height - 60, Screen_Width - 30, 330);
        //        v.frame = CGRectMake(15, iphone_height-40, iphone_width-30, 40);
        imv.frame = CGRectMake(iphone_width / 2 - (30 / 2), iphone_height - 30, 30, 30);
    } else {
        imv.frame = CGRectMake(iphone_width / 2 - (30 / 2), iphone_height, 30, 30);
        self.frame = CGRectMake(15, Screen_Height, Screen_Width - 30, 330);
    }
    //    [_view sendSubviewToBack:v];

    //    self.layer.cornerRadius = 20;
    //    self.myToolbar.layer.cornerRadius = 20;
    //    self.myToolbar.clipsToBounds = YES;
    // 设置圆角
    //       UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.myToolbar.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(20, 20)];
    //       CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //       maskLayer.frame = self.myToolbar.bounds;
    //       maskLayer.path = maskPath.CGPath;
    //       self.myToolbar.layer.mask = maskLayer;
}

- (void)MMK {
}

#pragma - 懒加载
- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}
#pragma - 数据源方法
// 一共多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

// 第component列显示多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.dataSource.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return 50;
}
#pragma - 代理方法
// 第component列的第row行显示什么文字
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return self.dataSource[row];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
//    UILabel* pickerLabel = (UILabel*)view;
//    if (!pickerLabel){
//        pickerLabel = [[UILabel alloc] init];
//
////        pickerLabel.font = [UIFont systemFontOfSize:10.];
//        pickerLabel.adjustsFontSizeToFitWidth = YES;
//        pickerLabel.textAlignment = UITextAlignmentCenter;
//        [pickerLabel setBackgroundColor:[UIColor clearColor]];
//        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
//    }
//    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
//    return pickerLabel;
//}

#pragma mark 打开与关闭方法
- (void)show {
    if (!self.dataSource.count) {
        return;
    }
    [self loadNibFile];
    [self loadUI];
    self.ClickdetermineBut.layer.cornerRadius = 10;
    self.contentView.layer.cornerRadius = 12;
    self.myPickerView.dataSource = self;
    self.myPickerView.delegate = self;
    if ([self.dataSource containsObject:self.defaultStr]) {
        NSInteger selectRow = [self.dataSource indexOfObject:self.defaultStr];
        [self.myPickerView selectRow:selectRow inComponent:0 animated:NO];
        self.honk = 1;
        //        UIView *v = [self.myPickerView]
        //        [self.myPickerView reloadAllComponents];
    }
    //    POPSpringAnimation *animation = [POPSpringAnimation animation];
    //    animation.property = [POPAnimatableProperty propertyWithName:kPOPLayerTranslationY];
    //    animation.fromValue = @0.0;
    //    animation.toValue = @-206.0;
    //    animation.springBounciness = 12.0;
    //    animation.springSpeed = 30.0;
    //    [self.layer pop_addAnimation:animation forKey:@"pop"];

    [UIView animateWithDuration:0.3
                     animations:^{
                       if (kIS_iPhoneX) {
                           self.frame = CGRectMake(15, Screen_Height - (330 + 60), Screen_Width - 30, 330);
                           _imv.frame = CGRectMake(iphone_width / 2 - (30 / 2), Screen_Height - (330 + 30) - 30, 30, 30);
                       } else {
                           _imv.frame = CGRectMake(iphone_width / 2 - (30 / 2), Screen_Height - (330) - 30, 30, 30);
                           self.frame = CGRectMake(15, Screen_Height - 330, Screen_Width - 30, 330);
                       }
                     }];
}
- (void)close {
    // 移除点击手势
    [_window removeGestureRecognizer:_gesture];
    _gesture = nil;
    [UIView animateWithDuration:0.2
        animations:^{
          _v.alpha = 0.0;
          _imv.frame = CGRectMake(iphone_width / 2 - (30 / 2), Screen_Height, 30, 30);
          self.frame = CGRectMake(15, Screen_Height, Screen_Width - 30, 330);
        }
        completion:^(BOOL finished) {
          [_view removeFromSuperview];
        }];
}
#pragma mark 确定
- (IBAction)clockDetermine:(id)sender {
}
#pragma mark 取消
- (IBAction)cancel:(id)sender {
    [self close];
}

// 点击了确定按钮
- (IBAction)clickBut:(id)sender {
    NSString *str = [self pickerView:self.myPickerView titleForRow:[self.myPickerView selectedRowInComponent:0] forComponent:0];

    if (self.block) {
        self.block(self, str, [self.myPickerView selectedRowInComponent:0]);
    }
    [self close];
}

// 判断是否在开始动画

// 选中了某一行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    UILabel *piketLabel = (UILabel *)[pickerView viewForRow:row forComponent:component];
    //    piketLabel.textColor = pickselecolor;
    [piketLabel setFont:[UIFont boldSystemFontOfSize:tRealFontSize(26)]];

    //    cust_Color(78,76,112,1)
    piketLabel.textColor = [UIColor blackColor];
    //    self.box = row; //保存
    //    [pickerView reloadComponent:0];//刷新
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    ((UIView *)[pickerView.subviews objectAtIndex:0]).backgroundColor = [UIColor clearColor];
    ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = [UIColor clearColor];

    UILabel *pickerLabel = (UILabel *)view;
    if (pickerLabel == nil) {
        pickerLabel = [[UILabel alloc] init];

        pickerLabel.frame = CGRectMake(0, 0, 150, 30);
        // Setup label properties - frame, font, colors etc

        // adjustsFontSizeToFitWidth property to YES
        pickerLabel.adjustsFontSizeToFitWidth = YES;    // 解决 改变大小 和 文本显示不全的问题

        [pickerLabel setTextAlignment:NSTextAlignmentCenter];

        [pickerLabel setBackgroundColor:[UIColor clearColor]];

        [pickerLabel setFont:[UIFont boldSystemFontOfSize:tRealFontSize(20)]];
        pickerLabel.textColor = [UIColor blackColor];
        if ([self.dataSource containsObject:self.defaultStr]) {
            NSInteger selectRow = [self.dataSource indexOfObject:self.defaultStr];
            if (self.honk == 1) {
                if (selectRow == row) {
                    [pickerLabel setFont:[UIFont boldSystemFontOfSize:tRealFontSize(26)]];
                    pickerLabel.textColor = [UIColor blackColor];
                    self.honk = 0;
                    //                       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    //                           UILabel *piketLabel =  (UILabel *)[pickerView viewForRow:row forComponent:0];
                    //                           [piketLabel setFont:[UIFont boldSystemFontOfSize:26]];
                    //
                    //                       });
                }
            } else {
                [pickerLabel setFont:[UIFont boldSystemFontOfSize:20]];
            }

            //        UIView *v = [self.myPickerView]
            //        [self.myPickerView reloadAllComponents];
        }
    }
    //    if (row == self.box) {
    //
    //        pickerLabel.textColor = pickselecolor;
    //    }else{
    //        pickerLabel.textColor = [UIColor blackColor];
    //    }

    // Fill the label text here

    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];

    return pickerLabel;
}

// pickerView滚动完成，防止选择不准确

- (BOOL)anySubViewScrolling:(UIView *)view {
    for (UIView *theSubView in view.subviews) {
        if ([self anySubViewScrolling:theSubView]) {
            return YES;
        }
    }
    return YES;
}

// 只需要在点击确定按钮的时候调用这个方法判断一下就可以了
//- (IBAction)confirmBtnPressed:(id)sender {
//     if ([self anySubViewScrolling:self.addressPickerView] ) {
//         return;
//     }

// 确定按钮的操作。。。
//}

//- (BOOL)anySubViewScrolling:(UIView *)view{
//
//    if ([view isKindOfClass:[UIScrollView class]]) {
//
//        UIScrollView *scrollView = (UIScrollView *)view;
//
//        if (scrollView.dragging || scrollView.decelerating) {
//            UILabel *piketLabel =  (UILabel *)[self.myPickerView viewForRow:self.box forComponent:0];
//            piketLabel.backgroundColor = [UIColor blackColor];
//
//            return YES;
//
//        }
//
//    }
//
//    for (UIView *theSubView in view.subviews) {
//
//       if ([self anySubViewScrolling:theSubView]) {
//           UILabel *piketLabel =  (UILabel *)[self.myPickerView viewForRow:self.box forComponent:0];
//            piketLabel.backgroundColor = [UIColor blackColor];
//           return YES;
//
//       }
//
//    }
//
//    return NO;
//
//}

@end
